package org.jeecg.glr.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.glr.entity.GlrColumn;
import org.jeecg.glr.entity.GlrLed;
import org.jeecg.glr.entity.GlrResource;
import org.jeecg.glr.service.IGlrColumnService;
import org.jeecg.glr.service.IGlrLedService;
import org.jeecg.glr.service.ILedCommon;
import org.jeecg.glr.util.GLRConstant;
import org.jeecg.glr.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.List;

 /**
 * @Description: 栏目内容
 * @Author: jeecg-boot
 * @Date:   2020-02-24
 * @Version: V1.0
 */
@RestController
@RequestMapping("/glr/glrColumn")
@Slf4j
public class GlrColumnController extends JeecgController<GlrColumn, IGlrColumnService> {
	@Autowired
	private IGlrColumnService glrColumnService;
     @Autowired
     private IGlrLedService glrLedService;

     @Resource
     ILedCommon ledCommon;
	 @Value(value = "${glr.path.projectPath}")
	 private String projectPath;
	/**
	 * 分页列表查询
	 *
	 * @param glrColumn
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@GetMapping(value = "/list")
	public Result<?> queryPageList(GlrColumn glrColumn,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<GlrColumn> queryWrapper = QueryGenerator.initQueryWrapperCode(glrColumn, req.getParameterMap());
		Page<GlrColumn> page = new Page<GlrColumn>(pageNo, pageSize);
		IPage<GlrColumn> pageList = glrColumnService.page(page, queryWrapper);
		return Result.ok(pageList);
	}
	
	/**
	 *   添加
	 *
	 * @param glrColumn
	 * @return
	 */
	@PostMapping(value = "/add")
	@AutoLog(value = "添加LED内容",logType= CommonConstant.LOG_TYPE_2)
	public Result<?> add(@RequestBody GlrColumn glrColumn) {
        glrColumn.setStatus(GLRConstant.YN_N);
        glrColumn.setReleaseDate(new Date());
        if(StringUtil.isEmpty(glrColumn.getStartTime())){
			glrColumn.setStartTime("00:00");
		}
		if(StringUtil.isEmpty(glrColumn.getEndTime())){
			glrColumn.setEndTime("23:59");
		}
        if(glrColumn.getTimespan()==0){
            glrColumn.setTimespan(20);
        }
		glrColumnService.save(glrColumn);
		return Result.ok("添加成功！");
	}
	
	/**
	 *  编辑
	 *
	 * @param glrColumn
	 * @return
	 */
	@PutMapping(value = "/edit")
	@AutoLog(value = "修改LED屏内容",logType= CommonConstant.LOG_TYPE_2)
	public Result<?> edit(@RequestBody GlrColumn glrColumn) {
		if(StringUtil.isEmpty(glrColumn.getStartTime())){
			glrColumn.setStartTime("00:00");
		}
		if(StringUtil.isEmpty(glrColumn.getEndTime())){
			glrColumn.setEndTime("23:59");
		}
		if(glrColumn.getTimespan()==0){
			glrColumn.setTimespan(20);
		}
		//如果修改，判断是否有相应资源或是设备，进行重新发布
		final List<GlrLed> ledCodeList=glrColumnService.getGlrLedByColunmId(glrColumn.getId());
		final List<GlrResource> resourceList =glrColumnService.getGlrLedResourceByColunmId(glrColumn.getId());
		if(ledCodeList!=null&&resourceList!=null){
			glrColumnService.publishColunm(ledCodeList,resourceList,glrColumn.getId());
			glrColumn.setStatus(GLRConstant.YN_Y);
		}
		glrColumnService.updateById(glrColumn);
		return Result.ok("编辑成功!");
	}
	
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@DeleteMapping(value = "/delete")
	@AutoLog(value = "删除LED屏管理内容",logType= CommonConstant.LOG_TYPE_2)
	public Result<?> delete(@RequestParam(name="id",required=true) String id) {
		glrColumnService.deleteGlrColumnByIds(id);
		return Result.ok("删除成功!");
	}
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "删除LED屏管理内容",logType= CommonConstant.LOG_TYPE_2)
	@DeleteMapping(value = "/deleteBatch")
	public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		glrColumnService.deleteGlrColumnByIds(ids);
		return Result.ok("批量删除成功!");
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@GetMapping(value = "/queryById")
	public Result<?> queryById(@RequestParam(name="id",required=true) String id) {
		GlrColumn glrColumn = glrColumnService.getById(id);
		if(glrColumn==null) {
			return Result.error("未找到对应数据");
		}
		return Result.ok(glrColumn);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param glrColumn
    */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, GlrColumn glrColumn) {
        return super.exportXls(request, glrColumn, GlrColumn.class, "栏目内容");
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, GlrColumn.class);
    }
	/**
	 *
	 * 功能描述: 发布资源到LED屏
	 *
	 * @param: 
	 * @return: 
	 * @auther: Administrator
	 * @date: 2020/3/5 14:50
	 */
	 @AutoLog(value = "发布LED屏",logType= CommonConstant.LOG_TYPE_2)
	 @RequestMapping(value = "/publishColunm", method = RequestMethod.POST)
	 public Result<?> publishColunm(HttpServletRequest request, HttpServletResponse response,@RequestBody GlrColumn glrColumn) {

		 final List<GlrLed> ledCodeList=glrColumnService.getGlrLedByColunmId(glrColumn.getId());
		 final List<GlrResource> resourceList =glrColumnService.getGlrLedResourceByColunmId(glrColumn.getId());
		 glrColumnService.publishColunm(ledCodeList,resourceList,glrColumn.getId());
         glrColumn.setStatus(GLRConstant.YN_Y);
         glrColumnService.updateById(glrColumn);
		 return Result.ok("发布成功");
	 }
	 /**
	  *
	  * 功能描述: 发布资源到LED屏
	  *
	  * @param:
	  * @return:
	  * @auther: Administrator
	  * @date: 2020/3/5 14:50
	  */
	 @RequestMapping(value = "/previewShow", method = RequestMethod.POST)
	 public Result<?> previewShow(HttpServletRequest request, HttpServletResponse response, @RequestBody GlrColumn glrColumn) {
		 final List<GlrResource> resourceList =glrColumnService.getGlrLedResourceByColunmId(glrColumn.getId());
		 for (GlrResource glr :
				 resourceList) {
			 glr.setFilePath(projectPath+glr.getFilePath());
		 }
		 return Result.ok(resourceList);
	 }

     /**
      *
      * 功能描述: 设置亮度
      *
      * @param:
      * @return:
      * @auther: Administrator
      * @date: 2020/3/12 10:23
      */
	 @AutoLog(value = "设置LED屏亮度",logType= CommonConstant.LOG_TYPE_2)
     @PostMapping(value = "/setBrightnessValue")
     public Result<?> setBrightnessValue(@RequestBody GlrColumn glrColumn)  {
         //如果ID不为空
         if(StringUtil.isNotEmpty(glrColumn.getIds())){
             String idsArr[]=glrColumn.getIds().split(",");
             for (String id : idsArr)
             {
                 try {
                     List<GlrLed> list=   glrColumnService.getLedCodeByCommonId(id);
                     for (GlrLed led :
                             list) {
                         try {
                             boolean flag=ledCommon.setBrightness(led.getCode(), glrColumn.getBrightness(),glrColumn.getDisabledValue());
                             if(flag){
                             	if(!glrColumn.getDisabledValue()){
									glrLedService.updateBrightnessByCodes(glrColumn.getBrightness(),led.getCode());
								}
                             }
                         } catch (IOException e) {
                             e.printStackTrace();
                         }
                     }
                 } catch (Exception e) {
                     e.printStackTrace();
                 }
             }

         }
         return Result.ok("操作成功");
     }

	 /**
	  * 开关LED屏
	  *
	  * @return
	  */
	 @PostMapping(value = "/ledOpenOrClose")
	 @AutoLog(value = "开关LED屏",logType= CommonConstant.LOG_TYPE_2)
	 public Result<?> ledOpenOrClose(@RequestBody GlrColumn glrColumn) throws  Exception{
		 //如果ID不为空
		 if (StringUtil.isNotEmpty(glrColumn.getIds())) {
			 String[] strids = glrColumn.getIds().split(",");
			 String str = "";
			 for (int i = 0; i < strids.length; i++) {
				 if (StringUtil.isNotEmpty(str)) {
					 String cloumnId=strids[i];
					 List<GlrLed> list=   glrColumnService.getLedCodeByCommonId(cloumnId);
					 for (GlrLed led :
							 list) {
						 ledCommon.OpenClose(led.getCode(), glrColumn.getStatus());
					 }
				 }
			 }
		 }
		 return Result.ok("操作成功");
	 }

}
